#include "StdAfx.h"
#include "DataParser.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <sstream>

DataParser::DataParser(void)
{
}

DataParser::~DataParser(void)
{
}

bool DataParser::Init( const std::wstring& filepath, CharItems& charitems )
{

	std::ifstream is;
	is.open(filepath.c_str(), std::ios::in);
	if (!is.is_open())
	{
		return false;
	}

	while(!is.eof())
	{
		char tmp[1024];
		is.getline(tmp, 1024);
		wchar_t wcs[1024];
		mbstowcs(wcs, tmp, 1024);
		
		charitems.insert(GetChatItem(wcs));
		
	}
	
	return true;
}

bool DataParser::Init( char* pData, int size, CharItems& charitems )
{
	std::istringstream is(pData, size);
// 	is.open(filepath.c_str(), std::ios::in);
// 		if (!is.is_open())
// 		{
// 			return false;
// 		}

	while(!is.eof())
	{
		char tmp[1024];
		is.getline(tmp, 1024);
		wchar_t wcs[1024];
		mbstowcs(wcs, tmp, 1024);

		charitems.insert(GetChatItem(wcs));

	}

	return true;
}

std::pair<wchar_t, CharItem> DataParser::GetChatItem( const std::wstring& parseString )
{
	std::pair<wchar_t, CharItem> ret;
	std::vector<std::wstring> wordAndpronounce;
	boost::split(wordAndpronounce, parseString, boost::is_any_of(L" "));
	if (wordAndpronounce.size() == 2)
	{
		ret.first = (wchar_t)HexStr2Int(wordAndpronounce[0]);
		ret.second = Pronounce2CharItem(wordAndpronounce[1]);
	}
	else
	{
		assert(0);
	}
	return ret;
}

int DataParser::HexStr2Int( const std::wstring& str )
{
	int ret;
	std::wstringstream convert(L"0x" + str);
	convert >> std::hex >> ret;
	return ret ;
}

CharItem DataParser::Pronounce2CharItem( const std::wstring& str )
{
	CharItem ret;
	std::wstring trimed = boost::trim_copy_if(str, boost::is_any_of(L"()"));
	boost::split(ret, trimed, boost::is_any_of(L","));
	return ret;
}